<template>
  <el-cascader
    size="medium"
    :options="hasAll ? provinceAndCityPlus : provinceAndCity"
    v-model="innerVal"
    @change="handleChange"
    :clearable="clearable"
  >
  </el-cascader>
</template>

<script>
import {
  provinceAndCityDataPlus,
  provinceAndCityData,
  TextToCode
} from 'element-china-area-data'
export default {
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    clearable: {
      type: Boolean,
      default() {
        return false
      }
    },
    hasAll: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    return {
      innerVal: []
    }
  },
  computed: {
    provinceAndCity() {
      return provinceAndCityData.map(e => {
        return {
          ...e,
          label: Utils.formatProvince(e.label)
        }
      })
    },
    provinceAndCityPlus() {
      return provinceAndCityDataPlus.map(e => {
        return {
          ...e,
          label: Utils.formatProvince(e.label)
        }
      })
    },
    textToCodeFormated() {
      let obj = {}
      for (let key in TextToCode) {
        obj[Utils.formatProvince(key)] = TextToCode[key]
      }
      return obj
    }
  },
  watch: {
    value(value) {
      if (value.length > 0 && isNaN(value[0])) {
        this.innerVal = [
          value[0] ? this.textToCodeFormated[value[0]].code : '',
          value[1] ? this.textToCodeFormated[value[0]][value[1]].code : ''
        ]
      }
    }
  },
  created() {
    if (this.value.length > 0) {
      this.innerVal = [
        this.value[0] ? this.textToCodeFormated[this.value[0]].code : '',
        this.value[1]
          ? this.textToCodeFormated[this.value[0]][this.value[1]].code
          : ''
      ]
    }
  },
  methods: {
    handleChange(value) {
      this.$emit('regionChange', value)
    }
  }
}
</script>
